package com.yanqu.road.server.gameplayer.module.activity.peakstronghold;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.peakstronghold.UserPeakStrongholdPatronsData;
import com.yanqu.road.entity.activity.peakstronghold.UserPeakStrongholdWarData;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongHoldConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongholdDonateConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.ePeakStrongholdStageType;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogPeakHoldSilverDonate;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.bussiness.player.activity.PeakStrongholdBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.RandomWeightConfigHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.peakstronghold.PeakStrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdWarMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class PeakStrongholdModule extends GeneralModule {

    private Map<Integer, UserPeakStrongholdWarData> userDataMap;

    private Map<Integer, Map<Integer, UserPeakStrongholdPatronsData>> patronsMap;

    private List<UserPatrons> topPatrons = new ArrayList<>();//缓存的前N名门客


    public PeakStrongholdModule(GamePlayer player) {
        super(player);
    }

    /**
     * 根据活动Id 获取据点战玩家个人数据
     *
     * @param activityId 活动id
     */
    public UserPeakStrongholdWarData getPeakStrongholdWarData(int activityId) {
        UserPeakStrongholdWarData data = userDataMap.get(activityId);
        if (data == null) {
            synchronized (userDataMap) {
                data = userDataMap.get(activityId);
                if (data == null) {
                    data = new UserPeakStrongholdWarData();
                    data.setActivityId(activityId);
                    data.setUserId(getUserId());
                    data.setDonateNumMap(new HashMap<>());
                    data.setInsertOption();
                    userDataMap.put(activityId, data);
                }
            }
        }

        //银两每轮清空,这里修正就行
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null != config) {
            if (data.getSilverRound() != config.getRound()) {
                data.setSilverRound(config.getRound());
                data.getDonateNumMap().clear();
//                data.setSilverAmount(BigInteger.ZERO);
                data.setUpdateOption();
            }
        }
        return data;
    }

    @Override
    public boolean loadData() {
        patronsMap = new ConcurrentHashMap<>();
        userDataMap = new ConcurrentHashMap<>();
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null != config && ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            int activityId = config.getActivityInfo().getActivityId();
            userDataMap = PeakStrongholdBusiness.getStrongholdWarUserData(getUserId());
            Map<Integer, UserPeakStrongholdPatronsData> dataMap = PeakStrongholdBusiness.getStrongholdPatronsMap(activityId, getUserId());
            patronsMap.put(activityId, dataMap);
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for (UserPeakStrongholdWarData data : new ArrayList<>(userDataMap.values())) {
            if (data.isInsertOption()) {
                PeakStrongholdBusiness.addStrongholdUserData(data);
            } else if (data.isUpdateOption()) {
                PeakStrongholdBusiness.updateStrongholdUserData(data);
            }
        }
        for (Map<Integer, UserPeakStrongholdPatronsData> dataMap : patronsMap.values()) {
            for (UserPeakStrongholdPatronsData data : dataMap.values()) {
                if (data.isInsertOption()) {
                    PeakStrongholdBusiness.addStrongholdPatrons(data);
                } else if (data.isUpdateOption()) {
                    PeakStrongholdBusiness.updateStrongholdPatrons(data);
                }
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        if (!SystemOpenMgr.systemOpen(player, eSystemId.PeakStrongholdActivity.getValue())) {
            return;
        }
        initTopAbilityPatrons();
        syncUserData();
        syncConfigData();
    }

    @Override
    public void loginSendMsg() {
        if (!SystemOpenMgr.systemOpen(player, eSystemId.PeakStrongholdActivity.getValue())) {
            return;
        }

        syncConfigData();
        syncUserData();
        noticeCrossUserLogin();
    }

    public void initSystem() {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        initTopAbilityPatrons();
        syncConfigData();
        syncUserData();
    }

    private void noticeCrossUserLogin(){
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config || null == config.getActivityInfo() || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        PeakStrongholdWarProto.CrossPeakHoldUserLoginReqMsg.Builder syncMsg= PeakStrongholdWarProto.CrossPeakHoldUserLoginReqMsg.newBuilder();
        syncMsg.setActivityId(config.getActivityInfo().getActivityId());
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_USER_LOGIN, syncMsg, syncMsg.getActivityId());
    }

    public void syncUserData() {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        resetBattlePatrons();
        PeakStrongholdWarProto.PeakStrongholdUserSyncDataMsg.Builder syncMsg= PeakStrongholdWarProto.PeakStrongholdUserSyncDataMsg.newBuilder();
        syncMsg.setHasQualification(PeakStrongholdActivityMgr.canUnionInBattle(player.getUserInfo().getUnionUid()));
        syncMsg.setStageType(config.getStageType().getValue());
        syncMsg.setNextStageTime(config.getNextStageTime());
        syncMsg.setRound(config.getRound());
        for (UserPatrons userPatrons : topPatrons) {
            syncMsg.addEliminateDefendPatronsId(userPatrons.getPatronsId());
        }
        Map<Integer, UserPeakStrongholdPatronsData> dataMap = patronsMap.get(config.getActivityInfo().getActivityId());
        if (dataMap != null) {
            for (UserPeakStrongholdPatronsData patronsData : dataMap.values()) {
                PeakStrongholdWarProto.PeakStrongholdWarPatronsDataTempMsg.Builder patronMsg = PeakStrongholdWarProto.PeakStrongholdWarPatronsDataTempMsg.newBuilder();
                patronMsg.setPatronsId(patronsData.getPatronsId());
                patronMsg.setBuyTimes(patronsData.getBuyTimes());
                patronMsg.setFreeTimes(patronsData.getFreeTimes());
                syncMsg.addPatrons(patronMsg.build());
            }
        }

        UserPeakStrongholdWarData holdData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());
        for (Map.Entry<Integer, Integer> donateMap : holdData.getDonateNumMap().entrySet()) {
            int donateId = donateMap.getKey();
            int donateNum = donateMap.getValue();
            PeakStrongholdWarProto.PeakStrongItemDonateTemp.Builder donateMsg = PeakStrongholdWarProto.PeakStrongItemDonateTemp.newBuilder();
            donateMsg.setDonateId(donateId);
            donateMsg.setNum(donateNum);
            syncMsg.addItemDonateInfo(donateMsg);
        }

        syncMsg.setIsWorship(holdData.isWorship());
        player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_USERDATA_SYNC, syncMsg);

        PeakStrongholdWarProto.CrossPeakHoldUnionBaseReqMsg.Builder crossMsg = PeakStrongholdWarProto.CrossPeakHoldUnionBaseReqMsg.newBuilder();
        crossMsg.setActivityId(config.getActivityInfo().getActivityId());
        String ownUnionUid = GameUnionActivityGroupMgr.getUnionUid(crossMsg.getActivityId(), player.getUserId());
        crossMsg.setUnionId(ownUnionUid);
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_UNION_BASE_DATA, crossMsg, crossMsg.getActivityId());
    }

    public void worship(){
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        PeakStrongholdWarProto.PeakHoldWorshipRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakHoldWorshipRespMsg.newBuilder();
        respMsg.setRet(0);
        UserPeakStrongholdWarData holdData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());
        if(holdData.isWorship()){
            respMsg.setRet(GameErrorCode.E_PEAK_HOLD_IS_WORSHIP);
            player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_WORSHIP, respMsg);
            return;
        }
        holdData.setWorship(true);
        String worshipReward = config.getWorshipReward();
        Property reward = PropertyHelper.parseStringToProperty(worshipReward);
        player.getModule(CurrencyModule.class).addCurrency(reward,eLogMoneyType.PeakStrongholdActivity,eLogMoneyType.PeakStrongholdActivityWorShip);
        respMsg.setReward(worshipReward);
        player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_WORSHIP, respMsg);

    }

    public void syncUserDataOnlyUser() {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        resetBattlePatrons();
        PeakStrongholdWarProto.PeakStrongholdUserSyncDataMsg.Builder syncMsg= PeakStrongholdWarProto.PeakStrongholdUserSyncDataMsg.newBuilder();
        syncMsg.setHasQualification(PeakStrongholdActivityMgr.canUnionInBattle(player.getUserInfo().getUnionUid()));
        syncMsg.setStageType(config.getStageType().getValue());
        syncMsg.setNextStageTime(config.getNextStageTime());
        syncMsg.setRound(config.getRound());
        for (UserPatrons userPatrons : topPatrons) {
            syncMsg.addEliminateDefendPatronsId(userPatrons.getPatronsId());
        }
        Map<Integer, UserPeakStrongholdPatronsData> dataMap = patronsMap.get(config.getActivityInfo().getActivityId());
        if (dataMap != null) {
            for (UserPeakStrongholdPatronsData patronsData : dataMap.values()) {
                PeakStrongholdWarProto.PeakStrongholdWarPatronsDataTempMsg.Builder patronMsg = PeakStrongholdWarProto.PeakStrongholdWarPatronsDataTempMsg.newBuilder();
                patronMsg.setPatronsId(patronsData.getPatronsId());
                patronMsg.setBuyTimes(patronsData.getBuyTimes());
                patronMsg.setFreeTimes(patronsData.getFreeTimes());
                syncMsg.addPatrons(patronMsg.build());
            }
        }

        UserPeakStrongholdWarData holdData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());
        for (Map.Entry<Integer, Integer> donateMap : holdData.getDonateNumMap().entrySet()) {
            int donateId = donateMap.getKey();
            int donateNum = donateMap.getValue();
            PeakStrongholdWarProto.PeakStrongItemDonateTemp.Builder donateMsg = PeakStrongholdWarProto.PeakStrongItemDonateTemp.newBuilder();
            donateMsg.setDonateId(donateId);
            donateMsg.setNum(donateNum);
            syncMsg.addItemDonateInfo(donateMsg);
        }
        syncMsg.setIsWorship(holdData.isWorship());
        player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_USERDATA_SYNC, syncMsg);
    }

    public void syncConfigData() {
        PeakStrongholdWarProto.SyncPeakStrongholaActivityMsg.Builder configMsg = PeakStrongholdActivityMgr.getConfigMsg(player.getLanguage());
        if(configMsg != null){
            player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_CONFIG_SYNC, configMsg);
        }
    }

    //初始化前N名门客
    public void initTopAbilityPatrons() {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }

        int topCount = config.getTopDefendPatronsNum();
        if (topCount <= 0) {
            return;
        }
        List<UserPatrons> userPatrons = player.getModule(PatronsModule.class).getUserPatronsList();

        userPatrons.sort((o1, o2) -> {
            BigInteger a1 = o1.getAbility();
            BigInteger a2 = o2.getAbility();
            return a2.compareTo(a1);
        });

        topPatrons.clear();
        for (UserPatrons patrons : userPatrons) {
            topPatrons.add(patrons.cloneUserPatrons());
            if (--topCount <= 0) {
                break;
            }
        }
    }

    //获得赚力排名前N的门客
    public List<UserPatrons> getTopEarnSpeedPatrons() {
        List<UserPatrons> result = new ArrayList<>();
        if (topPatrons.isEmpty()) {
            initTopAbilityPatrons();
        }
        result.addAll(topPatrons);
        return result;
    }

    public void notifyAddPatrons(UserPatrons userPatrons) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }

        int topCount = config.getTopDefendPatronsNum();
        if (topCount <= 0) {
            return;
        }
        replaceTopPatrons(userPatrons, config);

    }

    //判断前N名门客有没有变动,有就加入同步缓存
    public void checkStrongholdTopChange(UserPatrons userPatrons) {
        if (!SystemOpenMgr.systemOpen(player, eSystemId.PeakStrongholdActivity.getValue())) {
            return;
        }
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }

        int topCount = config.getTopDefendPatronsNum();
        if (topCount <= 0) {
            return;
        }

        boolean isChange = replaceTopPatrons(userPatrons, config);


        if (isChange) {
            topPatrons.sort((o1, o2) -> {
                BigInteger a1 = o1.getAbility();
                BigInteger a2 = o2.getAbility();
                return a2.compareTo(a1);
            });

            PeakStrongholdActivityMgr.addWaitTakeDefendMembers(player.getUserId());
        }
    }

    private boolean replaceTopPatrons(UserPatrons userPatrons, PeakStrongHoldConfig config) {

        boolean isChange = false;
        boolean isHave = false;
        if (config.getStageType() != ePeakStrongholdStageType.Prepare) {
            //不在准备期
            return false;
        }

        Map<Integer, UserPatrons> patronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        List<UserPatrons> topPatronsList = PeakStrongholdActivityMgr.getUserPatronsByEarnSpeedRank(config.getTopDefendPatronsNum(), new ArrayList<>(patronsMap.values()));


        if (topPatronsList.size() > topPatrons.size()) {
            // 如果比缓存的多 那就要改变
            isChange = true;
        }else {
            for (int i = 0; i < topPatronsList.size(); i++) {
                UserPatrons p1 = topPatronsList.get(i);
                UserPatrons p2 = topPatrons.get(i);
                if (p1.getPatronsId() != p2.getPatronsId() || p1.getAbility().compareTo(p2.getAbility()) != 0) {
                    isChange = true;
                }
            }
        }


        if (isChange) {
            topPatrons.clear();
            for (UserPatrons patrons : topPatronsList) {
                topPatrons.add(patrons.cloneUserPatrons());
            }
        }

      /*  for (UserPatrons patrons : topPatrons) {
            if (patrons.getPatronsId() == userPatrons.getPatronsId()) {
                isHave = true;
                if (patrons.getAbility().compareTo(userPatrons.getAbility()) != 0) {
                    isChange = true;
                }
                break;
            }
        }
        if (!isHave) {
            int topCount = config.getTopDefendPatronsNum();
            if (topPatrons.size() < topCount) {
                topPatrons.add(userPatrons.cloneUserPatrons());
                isChange = true;
            } else {
                int lastIdx = topPatrons.size() - 1;
                UserPatrons lastPatrons = topPatrons.get(lastIdx);
                if (lastPatrons.getAbility().compareTo(userPatrons.getAbility()) == -1) {
                    topPatrons.remove(lastIdx);
                    topPatrons.add(userPatrons.cloneUserPatrons());
                    isChange = true;
                }
            }
        }
        if (isChange) {
            topPatrons.sort((o1, o2) -> {
                BigInteger a1 = o1.getAbility();
                BigInteger a2 = o2.getAbility();
                return a2.compareTo(a1);
            });
        }*/
        return isChange;
    }

    // 道具捐献
    public int itemDonate(int donateId, int num) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        PeakStrongholdDonateConfig donateConfig = config.getDonateConfigMap().get(donateId);
        if (null == donateConfig || 0 == num) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_CONFIT_NOT_FOUND;
        }

        int maxNum = donateConfig.getMaxNum();
        if (0 == maxNum) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_CONFIT_NOT_FOUND;
        }

        UserPeakStrongholdWarData holdData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());

        if (maxNum > 0 && holdData.getDonateNum(donateId) >= maxNum) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_NUM_LIMIT;
        }

        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);

        Property cost = PropertyHelper.parseStringToProperty(donateConfig.getConsume());
        cost.goodCountMultiNum(num);
        if (!currencyModule.currencyIsEnough(cost)) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_COST_NOT_ENOUGH;
        }

        GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(Integer.valueOf(donateConfig.getRewards()));
        if (goodsInfo == null) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_CONFIT_NOT_FOUND;
        }

        Property reward = new Property();
        for (int i = 0; i < num; i++) {
            String extendParam = goodsInfo.getExtendParam();
            Property property = RandomWeightConfigHelper.getRandomProperty(extendParam);
            reward.addProperty(property);
        }

        if (!currencyModule.removeCurrency(cost, eLogMoneyType.PeakStrongholdActivity, eLogMoneyType.PeakStrongholdActivityDonateItem)) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_COST_NOT_ENOUGH;
        }

        if (!reward.isNothing()) {
            currencyModule.addCurrency(reward, eLogMoneyType.PeakStrongholdActivity, eLogMoneyType.PeakStrongholdActivityDonateItem);
        }

        int expAdd = donateConfig.getExp() * num;
        holdData.setDonateExp(holdData.getDonateExp() + expAdd);
        holdData.addDonateNum(donateId, num);
        holdData.setUpdateOption();

        PeakStrongholdWarProto.PeakStrongholdItemDonateRespMsg.Builder respMsg = PeakStrongholdWarProto.PeakStrongholdItemDonateRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(PropertyHelper.parsePropertyToString(reward));
        respMsg.setExpAdd(expAdd);

        player.sendPacket(Protocol.U_PEAK_STRONGHOLD_ITEM_DONATE_REQ, respMsg);

        syncUserDataOnlyUser();
        String unionId = GameUnionActivityGroupMgr.getUnionUid(config.getActivityInfo().getActivityId(), player.getUserId());
        PeakStrongholdWarProto.CrossPeakHoldItemDonateReq.Builder crossMsg = PeakStrongholdWarProto.CrossPeakHoldItemDonateReq.newBuilder();
        crossMsg.setActivityId(config.getActivityInfo().getActivityId());
        crossMsg.setUnionId(unionId);
        crossMsg.setDonateExp(holdData.getDonateExp());
        crossMsg.setDonateId(donateId);
        crossMsg.setRewards(respMsg.getReward());
        crossMsg.setDonateNum(num);
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_ITEM_DONATE_REQ, crossMsg, crossMsg.getActivityId());

        //额外同步一次,保险用
        PeakStrongholdActivityMgr.addWaitTakeDefendMembers(player.getUserId());

        return 0;
    }

    //银两捐献
    public int silverDonate(BigInteger silverNum) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        Property cost = new Property(GameConfig.GAME_MONEY_SILVER, silverNum);
        CurrencyModule currencyModule = player.getModule(CurrencyModule.class);
        if (!currencyModule.removeCurrency(cost, eLogMoneyType.PeakStrongholdActivity, eLogMoneyType.PeakStrongholdActivityDonateSilver)) {
            return GameErrorCode.E_PEAK_HOLD_DONATE_COST_NOT_ENOUGH;
        }

        UserPeakStrongholdWarData holdData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());
        holdData.addSilverAmount(silverNum);

        PeakStrongholdWarProto.CrossPeakHoldSilverDonateReq.Builder crossMsg = PeakStrongholdWarProto.CrossPeakHoldSilverDonateReq.newBuilder();
        crossMsg.setActivityId(config.getActivityInfo().getActivityId());
        String ownUnionUid = GameUnionActivityGroupMgr.getUnionUid(crossMsg.getActivityId(), player.getUserId());
        crossMsg.setUnionId(ownUnionUid);
        crossMsg.setTotalSilver(holdData.getSilverAmount().toString());
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_SILVER_DONATE_REQ, crossMsg, crossMsg.getActivityId());

        AutoLogMgr.add(new LogPeakHoldSilverDonate(config.getActivityInfo().getActivityId(), config.getRound(), player.getUserId(), silverNum.toString()));

        return 0;
    }

    public void resetBattlePatrons() {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        int activityId = config.getActivityInfo().getActivityId();
        int round = config.getRound();
        if (round <= 0) {
            return;
        }
        UserPeakStrongholdWarData userData = getPeakStrongholdWarData(activityId);
        if (userData.getResetPatronsRound() < round) {
            userData.setResetPatronsRound(round);
            Map<Integer, UserPeakStrongholdPatronsData> dataMap = patronsMap.get(activityId);
            if (dataMap != null) {
                for (UserPeakStrongholdPatronsData data : dataMap.values()) {
                    data.setFreeTimes(0);
                    data.setBuyTimes(0);
                }
            }
            syncUserData();
        }
    }

    //进攻据点
    public int attackUnionHold(String targetUnionId, int patronsId) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        String ownUninId = GameUnionActivityGroupMgr.getUnionUid(config.getActivityInfo().getActivityId(), player.getUserId());
        if (Objects.equals(ownUninId, targetUnionId)) {
            return GameErrorCode.E_PEAK_HOLD_CAN_NOT_ATTACK_SELF_UNION;
        }
        Map<Integer, UserPatrons> userPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        UserPatrons patrons = userPatronsMap.get(patronsId);
        if (patrons == null) {
            return GameErrorCode.E_PATRONS_NO_FOUND;
        }
        int activityId = config.getActivityInfo().getActivityId();
        resetBattlePatrons();
        Map<Integer, UserPeakStrongholdPatronsData> dispatchMap = patronsMap.get(activityId);
        Property consume = null;
        if (dispatchMap != null) {
            UserPeakStrongholdPatronsData data = dispatchMap.get(patronsId);
            if (data != null) {
                if (data.getFreeTimes() >= config.getEliminateFreeTimes()) {
                    int buyTimes = data.getBuyTimes();
                    if (buyTimes >= config.getEliminateBuyTimes()) {
                        return GameErrorCode.E_STRONGHOLD_PATRONS_BATTLE_TIMES_MAX;
                    }
                    consume = config.getEliminateConsume(buyTimes);
                    if (null == consume) {
                        return GameErrorCode.E_BAG_ITEM_NO_EXIST;
                    }
                    if (!player.getModule(CurrencyModule.class).currencyIsEnough(consume)) {
                        return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
                    }
                }
            }
        }
        if (consume != null) {
            player.getModule(PreReduceModule.class).preReduce(consume);
        }

        PeakStrongholdWarProto.CrossAttackEliminatePatronsReqMsg.Builder crossMsg = PeakStrongholdWarProto.CrossAttackEliminatePatronsReqMsg.newBuilder();
        crossMsg.setActivityId(activityId);
        crossMsg.setUnionId(ownUninId);
        crossMsg.setTargetUnionId(targetUnionId);
        long otherAddition = StrongholdWarMgr.getOtherAddition(player);
        crossMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        crossMsg.setPatronsId(patronsId);
        BigInteger totalAbility = StrongholdWarMgr.calcStrongholdPatronsTotalAbility(patrons, userPatronsMap, otherAddition);
        crossMsg.setDamage(totalAbility.toString());
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_ELIMINATION_ATTACK, crossMsg, config.getActivityInfo().getActivityId());

        return 0;
    }

    public UserPeakStrongholdPatronsData getChallengePatronsData(int activityId, int patronsId) {
        Map<Integer, UserPeakStrongholdPatronsData> dispatchMap = patronsMap.get(activityId);
        if (null != dispatchMap) {
            return dispatchMap.get(patronsId);
        }

        return null;
    }

    //更新玩家总伤害
    public void setTotalDamage(BigInteger damage) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        UserPeakStrongholdWarData userData = getPeakStrongholdWarData(config.getActivityInfo().getActivityId());
        userData.setTotalDamage(damage);

        player.notifyListener(eGamePlayerEventType.PeakStrongHoldUserDamageRank.getValue(), damage);
    }

    /**
     * 增加门客派遣次数
     *
     * @param patronsId
     */
    public void addBattlePatrons(int patronsId) {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (null == config) {
            return;
        }
        if (patronsId <= 0) {
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        if (activityInfo != null) {
            int activityId = activityInfo.getActivityId();
            Map<Integer, UserPeakStrongholdPatronsData> dataMap = patronsMap.get(activityId);
            if (dataMap == null) {
                dataMap = new ConcurrentHashMap<>();
                patronsMap.put(activityId, dataMap);
            }
            UserPeakStrongholdPatronsData patronsData = dataMap.get(patronsId);
            if (patronsData == null) {
                patronsData = new UserPeakStrongholdPatronsData();
                patronsData.setActivityId(activityId);
                patronsData.setUserId(getUserId());
                patronsData.setPatronsId(patronsId);
                patronsData.setInsertOption();
                dataMap.put(patronsId, patronsData);
            }
            int freeTimes = config.getEliminateFreeTimes();
            if (patronsData.getFreeTimes() >= freeTimes) {
                patronsData.setBuyTimes(patronsData.getBuyTimes() + 1);
            } else {
                patronsData.setFreeTimes(patronsData.getFreeTimes() + 1);
            }
            syncUserData();
            //珍兽绑定 鱼类绑定
            player.getModule(VehicleModule.class).bindPatrons(patronsId, activityId);
        }
    }

}
